import $ from 'jquery'

/**
 * 初始化流程图的方法
 * @author                  pre_liuwei
 * @param divID             用于展示流程图的div的id
 * @param jsonDataObjArr    流程图的json数据
 */
export function initRaphael(divID, jsonDataObjArr) {
  if (jsonDataObjArr.length === 0) {
    $('#' + divID).empty()
    return
  }
  $('#' + divID).empty()
  // debugger;
  var wfJsonArrStep = {}
  var Xs = []
  var wfJsonArrLine = {}
  implStep = []
  //拖动节点开始时的事件
  $.each(jsonDataObjArr, function (index, jsonDataObj) {
    wfJsonArrStep = jsonDataObj.Step
    wfJsonArrLine = jsonDataObj.Path
  })
  $.each(wfJsonArrStep, function (idx, wfOneStep) {
    if (wfOneStep) {
      Xs.push(wfOneStep.PRES_X)
      Xs.push(wfOneStep.PRES_Y)
    }
  })
  var Ys = []

  $.each(wfJsonArrStep, function (idx, wfOneStep) {
    if (wfOneStep) {
      Ys.push(wfOneStep.PRES_Y)
    }
  })
  Ys.sort(function (a, b) {
    return a - b
  })
  var maxY = Ys[Ys.length - 1] + 50
  //排序
  Xs.sort(function (a, b) {
    return a - b
  })
  var minX = Xs[0]

  //用来存储节点的顺序
  var connections = []
  //用来存储节点
  var shapes = []

  //用来存储节点的文本
  var texts = []
  var images = []
  //拖动事件
  var dragger = function () {
    this.ox = this.attr('x')
    this.oy = this.attr('y')
    this.animate({ 'fill-opacity': 0.2 }, 500)
  }
  //拖动结束后的事件
  var move = function (dx, dy) {
    var ws = 0
    var hs = 0
    for (var i = 0; i < wfJsonArrStep.length; i++) {
      if (
        wfJsonArrStep[i].PRES_NAME != '开始' &&
        wfJsonArrStep[i].PRES_NAME != '结束'
      ) {
        ws = parseInt(wfJsonArrStep[i].PRES_WIDTH)
        hs = parseInt(wfJsonArrStep[i].PRES_HEIGHT)
      }
    }

    var att = { x: this.ox + dx, y: this.oy + dy }
    this.attr(att)
    for (var j = texts.length; j--; ) {
      ws = parseInt(wfJsonArrStep[j].PRES_WIDTH)
      hs = parseInt(wfJsonArrStep[j].PRES_HEIGHT)
      if (texts[j].id == 'text' + this.id) {
        console.log(' texts[j].attr("x") ' + texts[j].attr('x'))
        var attText = { x: this.ox + dx + ws / 2, y: this.oy + dy + hs + 5 }
        texts[j].attr(attText)
        break
      }
    }
    for (var i = connections.length; i--; ) {
      r.drawArr(connections[i])
    }
    // 重新记录位置
    setImplStep()
  }
  var up = function () {
    this.animate({ 'fill-opacity': 1 }, 500)
  }

  //计算所需画布的大小
  var svgWidth = Xs[Xs.length - 1] - Xs[0] + 200
  var svgHeight = Ys[Ys.length - 1] - Ys[0] + 200

  //创建绘图对象
  var r = new Raphael(divID, svgWidth, svgHeight)

  function setColor(type) {
    if (type == 'INWORK') {
      return '#f6f7ff'
    } else if (type == 'UNDERREVIEW') {
      return '#336699'
    } else if (type == 'APPROVED') {
      return '#00DB00'
    } else if (type == 'REJECTED') {
      return '#FF1111'
    }
  }

  //绘制节点
  //绘制节点
  for (var i = 0; i < wfJsonArrStep.length; i++) {
    var x0 = parseInt(wfJsonArrStep[i].PRES_X) - minX + 40
    var y0 = parseInt(wfJsonArrStep[i].PRES_Y) - minX + 40
    var w0 = parseInt(wfJsonArrStep[i].PRES_WIDTH)
    var h0 = parseInt(wfJsonArrStep[i].PRES_HEIGHT)
    if (wfJsonArrStep[i].icon !== '') {
      var t = '/static/wfsvg/' + wfJsonArrStep[i].icon + '.svg'
      var w, h
      $.ajax({
        url: t,
        dataType: 'xml',
        type: 'get',
        async: false,
        success: function (xml) {
          w = $(xml).find('svg').eq(0).attr('width')
          h = $(xml).find('svg').eq(0).attr('height')
          w = w.substring(0, w.length - 2)
          h = h.substring(0, h.length - 2)
        },
      })

      shapes[i] = r
        .image(
          '/static/wfsvg/' + wfJsonArrStep[i].icon + '.svg',
          x0 - w / 2,
          y0 - h / 2,
          w,
          h
        )
        .attr({ cursor: 'move' })
      shapes[i].id = wfJsonArrStep[i].rowkey
      shapes[i].desc = wfJsonArrStep[i].PRES_DESC
      shapes[i].name = wfJsonArrStep[i].PRES_NAME
      wfJsonArrStep[i].PRES_WIDTH = w
      wfJsonArrStep[i].PRES_HEIGHT = h
      texts[i] = r.text(x0, y0 + h / 2 + 5, wfJsonArrStep[i].PRES_NAME).attr({
        font: '12px "Arial"',
        'fill-opacity': 1,
        cursor: 'move',
      })
      texts[i].id = 'text' + wfJsonArrStep[i].rowkey
      images[i] = r.image('', x0 + w0 - 32, y0 - 16, 0, 0)
      images[i].id = 'images' + wfJsonArrStep[i].rowkey
      shapes[i].stepType = wfJsonArrStep[i].PRES_STEPTYPE
    } else if (wfJsonArrStep[i].PRES_STEPTYPE === 'end') {
      shapes[i] = r.image('/images/stop48.png', x0, y0, 40, 40)
      shapes[i].id = wfJsonArrStep[i].rowkey
      shapes[i].desc = wfJsonArrStep[i].PRES_DESC
      shapes[i].name = wfJsonArrStep[i].PRES_NAME
      texts[i] = r.text(x0 + w / 2, y0 + h / 2, '').attr({
        font: '12px "Arial"',
        'fill-opacity': 1,
        cursor: 'move',
      })
      texts[i].id = 'text' + wfJsonArrStep[i].rowkey
      shapes[i].stepType = wfJsonArrStep[i].PRES_STEPTYPE
      images[i] = r.image('', x0 + w0 - 32, y0 - 16, 0, 0)
      images[i].id = 'images' + wfJsonArrStep[i].rowkey
    } else if (wfJsonArrStep[i].PRES_STEPTYPE === 'link') {
      var owner = ''
      if (wfJsonArrStep[i].PRES_OWNER) {
        owner = wfJsonArrStep[i].PRES_OWNER_NAME
      } else {
        owner = ''
      }
      shapes[i] = r.rect(x0, y0, w0, h0, 4).attr({
        fill: setColor(wfJsonArrStep[i].PRES_STATUS),
        stroke: '#808080',
        'stroke-width': '2px',
        'fill-opacity': 1,
        cursor: 'move',
        opacity: '.4',
      })
      shapes[i].id = wfJsonArrStep[i].rowkey
      shapes[i].desc = wfJsonArrStep[i].PRES_DESC
      shapes[i].name = wfJsonArrStep[i].PRES_NAME
      shapes[i].pres_owner_name = wfJsonArrStep[i].PRES_OWNER_NAME
      texts[i] = r
        .text(
          x0 + w0 / 2,
          y0 + h0 / 2,
          wfJsonArrStep[i].PRES_NAME + '\n' + owner
        )
        .attr({
          font: '12px "Arial"',
          'fill-opacity': 1,
          cursor: 'move',
        })
      if (wfJsonArrStep[i].PRES_STATUS === 'APPROVED') {
        images[i] = r
          .image('/images/approved32.png', x0 + w0 - 22, y0, 20, 20)
          .attr({ cursor: 'move' })
        images[i].id = 'images' + wfJsonArrStep[i].rowkey
      } else if (wfJsonArrStep[i].PRES_STATUS === 'REJECTED') {
        images[i] = r
          .image('/images/rejected32.png', x0 + w0 - 22, y0 + h0 - 20, 20, 20)
          .attr({ cursor: 'move' })
        images[i].id = 'images' + wfJsonArrStep[i].rowkey
      } else {
        images[i] = r.image('', x0 + w0 - 32, y0 - 16, 0, 0)
        images[i].id = 'images' + wfJsonArrStep[i].rowkey
      }
      texts[i].id = 'text' + wfJsonArrStep[i].rowkey
      shapes[i].stepType = wfJsonArrStep[i].PRES_STEPTYPE
      shapes[i].toFront()
    } else {
      var owner = ''
      if (wfJsonArrStep[i].PRES_OWNER) {
        owner = wfJsonArrStep[i].PRES_OWNER_NAME
      } else {
        owner = ''
      }
      if (wfJsonArrStep[i].PRES_STATUS === 'APPROVED') {
        images[i] = r
          .image('/images/approved32.png', x0 + w0 - 22, y0, 20, 20)
          .attr({ cursor: 'move' })
        images[i].id = 'images' + wfJsonArrStep[i].rowkey
      } else if (wfJsonArrStep[i].PRES_STATUS === 'REJECTED') {
        images[i] = r
          .image('/images/rejected32.png', x0 + w0 - 22, y0 + h0 - 20, 20, 20)
          .attr({ cursor: 'move' })
        images[i].id = 'images' + wfJsonArrStep[i].rowkey
      } else {
        images[i] = r.image('', x0 + w0 - 32, y0 - 16, 0, 0)
        images[i].id = 'images' + wfJsonArrStep[i].rowkey
      }
      shapes[i] = r.rect(x0, y0, w0, h0, 4).attr({
        fill: setColor(wfJsonArrStep[i].PRES_STATUS),
        stroke: '#187142',
        'stroke-width': '3px',
        'fill-opacity': 1,
        cursor: 'move',
        opacity: '.4',
      })
      shapes[i].id = wfJsonArrStep[i].rowkey
      shapes[i].desc = wfJsonArrStep[i].PRES_DESC
      shapes[i].name = wfJsonArrStep[i].PRES_NAME
      shapes[i].pres_owner_name = wfJsonArrStep[i].PRES_OWNER_NAME
      shapes[i].stepType = wfJsonArrStep[i].PRES_STEPTYPE
      texts[i] = r
        .text(
          x0 + w0 / 2,
          y0 + h0 / 2,
          wfJsonArrStep[i].PRES_NAME + '\n' + owner
        )
        .attr({
          font: '12px "Arial"',
          'fill-opacity': 1,
          cursor: 'move',
        })
      texts[i].id = 'text' + wfJsonArrStep[i].rowkey
      shapes[i].toFront()
    }
    shapes[i].pres_owner = wfJsonArrStep[i].PRES_OWNER
    shapes[i].dealRole = wfJsonArrStep[i].PRES_DEAL_ROLE
    shapes[i].dealRoleRowKey = wfJsonArrStep[i].PRES_DEAL_ROLEROWKEY
    shapes[i].pre_sort = wfJsonArrStep[i].PRES_SORT
    shapes[i].pre_mark = wfJsonArrStep[i].PRES_MARK
    shapes[i].pre_type = wfJsonArrStep[i].PRES_STATUS
    shapes[i].drag(move, dragger, up)

    //定义双击事件
    shapes[i].click(function () {
      var sh = this
      $.each(shapes, function (idx, oneshape) {
        if (!oneshape) {
        } else {
          if (sh === oneshape) {
            oneshape.attr('stroke', 'red')
          } else {
            if (oneshape.stepType === 'link') {
              oneshape.attr('stroke', '#808080')
            } else {
              oneshape.attr('stroke', '#187142')
            }
          }
        }
      })
    })
  }
  //绘制节点之间的连线
  $.each(wfJsonArrLine, function (index, lineData) {
    var fromID = lineData.fromstep
    var toID = lineData.tostep
    var fromStepObject = {}
    var toStepObject = {}
    for (var j = 0; j < shapes.length; j++) {
      var flag1 = 0
      var flag2 = 0
      if (fromID == shapes[j].id) {
        fromStepObject = shapes[j]
        flag1 = 1
      }

      if (toID == shapes[j].id) {
        toStepObject = shapes[j]
        flag2 = 1
      }
      if (flag1 == 1 && flag2 == 1) break
    }
    connections.push(
      r.drawArr({
        obj1: fromStepObject,
        obj2: toStepObject,
        PRES_CATEGORY: 'wfpathobj',
        type: lineData.type,
      })
    )
  })
  setImplStep()

  //将节点信息转换成需要存储的类型，每次移动后，执行该方法，重新记录位置
  function setImplStep() {
    implStep = []
    for (var i = 0; i < shapes.length; i++) {
      if (!shapes[i]) {
      } else {
        var saveSon = {}
        saveSon.rowkey = shapes[i].id
        saveSon.PRES_ID = shapes[i].id
        saveSon.PRES_NAME = shapes[i].name
        saveSon.PRES_DESC = shapes[i].desc
        saveSon.PRES_CATEGORY = 'wfstepobj'
        saveSon.PRES_STEPTYPE = shapes[i].stepType
        saveSon.PRES_X = shapes[i].attrs.x
        saveSon.PRES_Y = shapes[i].attrs.y
        saveSon.PRES_WIDTH = shapes[i].attrs.width
        saveSon.PRES_HEIGHT = shapes[i].attrs.height
        saveSon.PRES_MARK = shapes[i].pre_mark
        saveSon.PRES_SORT = shapes[i].pre_sort
        saveSon.PRES_STATUS = shapes[i].pre_type
        saveSon.PRES_OWNER = shapes[i].pres_owner
        saveSon.PRES_DEAL_ROLE = shapes[i].dealRole
        saveSon.STATUS = '-'
        saveSon.PRES_DEAL_ROLEROWKEY = shapes[i].dealRoleRowKey
        implStep.push(saveSon)
      }
    }
  }

  console.log(implStep)
  console.log('initRaphael end ---------------')
}

var implStep = []

var AllStepAndPath = []
var assist = []

//随着节点位置的改变动态改变箭头
Raphael.fn.drawArr = function (obj) {
  var point = getStartEnd(obj.obj1, obj.obj2)
  var path1
  if (obj.type === 'line') {
    path1 = getArrLine(
      point.start.x,
      point.start.y,
      point.end.x,
      point.end.y,
      8
    )
  } else {
    path1 = getArr(point.start.x, point.start.y, point.end.x, point.end.y, 8)
  }
  if (obj.arrPath) {
    obj.arrPath.attr({ path: path1 })
  } else {
    obj.arrPath = this.path(path1)
    AllStepAndPath.push(obj.arrPath)
    assist = AllStepAndPath
  }
  obj.arrPath.attr({ stroke: '#444444', 'stroke-width': 1.2 })
  return obj
}

//动态确定起点和终点的方法
function getStartEnd(obj1, obj2) {
  var bb1 = obj1.getBBox(),
    bb2 = obj2.getBBox()
  var p = [
    { x: bb1.x + bb1.width / 2, y: bb1.y - 1 },
    { x: bb1.x + bb1.width / 2, y: bb1.y + bb1.height + 1 },
    { x: bb1.x - 1, y: bb1.y + bb1.height / 2 },
    { x: bb1.x + bb1.width + 1, y: bb1.y + bb1.height / 2 },
    { x: bb2.x + bb2.width / 2, y: bb2.y - 1 },
    { x: bb2.x + bb2.width / 2, y: bb2.y + bb2.height + 1 },
    { x: bb2.x - 1, y: bb2.y + bb2.height / 2 },
    { x: bb2.x + bb2.width + 1, y: bb2.y + bb2.height / 2 },
  ]
  var d = {},
    dis = []
  for (var i = 0; i < 4; i++) {
    for (var j = 4; j < 8; j++) {
      var dx = Math.abs(p[i].x - p[j].x),
        dy = Math.abs(p[i].y - p[j].y)
      if (
        i == j - 4 ||
        (((i != 3 && j != 6) || p[i].x < p[j].x) &&
          ((i != 2 && j != 7) || p[i].x > p[j].x) &&
          ((i != 0 && j != 5) || p[i].y > p[j].y) &&
          ((i != 1 && j != 4) || p[i].y < p[j].y))
      ) {
        dis.push(dx + dy)
        d[dis[dis.length - 1]] = [i, j]
      }
    }
  }
  if (dis.length == 0) {
    var res = [0, 4]
  } else {
    res = d[Math.min.apply(Math, dis)]
  }
  var result = {}
  result.start = {}
  result.end = {}
  result.start.x = p[res[0]].x
  result.start.y = p[res[0]].y
  result.end.x = p[res[1]].x
  result.end.y = p[res[1]].y
  return result
}

//获取组成箭头的三条线段的路径
function getArr(x1, y1, x2, y2, size) {
  var angle = Raphael.angle(x1, y1, x2, y2) //得到两点之间的角度
  var a45 = Raphael.rad(angle - 36) //角度转换成弧度
  var a45m = Raphael.rad(angle + 36)
  var x2a = x2 + Math.cos(a45) * size
  var y2a = y2 + Math.sin(a45) * size
  var x2b = x2 + Math.cos(a45m) * size
  var y2b = y2 + Math.sin(a45m) * size
  var result = [
    'M',
    x1,
    y1,
    'L',
    x2,
    y2,
    'L',
    x2a,
    y2a,
    'M',
    x2,
    y2,
    'L',
    x2b,
    y2b,
  ]
  return result
}

//获取直线路径
function getArrLine(x1, y1, x2, y2, size) {
  var angle = Raphael.angle(x1, y1, x2, y2) //得到两点之间的角度
  // var a45 = Raphael.rad(angle - 36);//角度转换成弧度
  // var a45m = Raphael.rad(angle + 36);
  // var x2a = x2 + Math.cos(a45) * size;
  // var y2a = y2 + Math.sin(a45) * size;
  // var x2b = x2 + Math.cos(a45m) * size;
  // var y2b = y2 + Math.sin(a45m) * size;
  var result = ['M', x1, y1, 'L', x2, y2]
  return result
}

var savePath = []

/**
 * 手动绘制流程的方法
 * @author liuwei
 * @param divID     放置流程图的div的id
 * @param divWidth  div的宽度
 * @param divHeight div的高度
 * @param main      最外层的mainDiv
 * @param rowkey    用于确定对象的rowkey
 * @constructor
 */
export function AddRaphael(divID, divWidth, divHeight, main, rowkey) {
  //用来显示连线和选择的状态
  var $stateSpan = $(
    '<div class="PreWebWorkFlow_AddWFTemplate_stateSpan"></div>'
  )
  $('#WFAddmyflow').append($stateSpan)
  //存储我们新建的这条模板数据的url
  var url = ''
  //存储保存时的节点数组数据
  var saveStep = []
  //存储保存时需要的path数据
  savePath = []

  /*drag($props);*/
  //用来存储节点的顺序
  var connections = []
  //用来存储节点
  var shapes = []
  //用来存储节点的文本
  var texts = []

  //拖动节点开始时的事件
  var dragger = function () {
    this.ox = this.attr('x')
    this.oy = this.attr('y')
    this.animate({ 'fill-opacity': 0.2 }, 500)
  }
  //截掉最后一个/后面的字符串
  var str = rowkey
  var index = str.lastIndexOf('/')
  str = str.substring(index + 1, -str.length)

  //拖动事件
  var move = function (dx, dy) {
    var att = { x: this.ox + dx, y: this.oy + dy }
    this.attr(att)
    console.log(this.id)
    for (var j = shapes.length; j--; ) {
      if ($.isEmptyObject(shapes[j])) {
      } else {
        if (shapes[j].text.id == 'text' + this.id) {
          var attText = { x: this.ox + dx + 50, y: this.oy + dy + 25 }
          shapes[j].text.attr(attText)
          break
        }
      }
    }
    for (var i = connections.length; i--; ) {
      r.drawArr(connections[i])
    }
  }
  //拖动结束后的事件
  var up = function () {
    this.animate({ 'fill-opacity': 1 }, 500)
  }
  //创建绘图对象
  var r = new Raphael(divID, divWidth, divHeight)

  //i用来标记节点的顺序序号
  var i = 0
  //s用来标志状态，0是选择元素，1是连线中
  var s = 0
  /*  用来存储连线的开始节点和结束节点
      obj1是起始的节点
      obj2是指向的节点
   */
  var obj1 = []
  var obj2 = []

  //n标志是否可以画线，0不可以，1可以
  var n = 0
  //存放rowkey
  url = rowkey
  /*开始标签*/
  $('#start').mousedown(function () {
    CrateStep('start')
  })
  /*环节标签*/
  $('#state').mousedown(function () {
    CrateStep('link')
  })
  /*会签标签*/
  $('#countersign').mousedown(function () {
    CrateStep('countersign')
  })
  /*结束标签*/
  $('#end').mousedown(function () {
    CrateStep('end')
  })

  function setOption(select, role, rowKey) {
    $.ajax({
      url: '/preplatform/prewf/wfimpcom/searchSpecialty',
      type: 'get',
      dataType: 'json',
      success: function (responseData) {
        var arrOption = responseData.response.data
        $.each(arrOption, function (i, option) {
          var $option = $('<option></option>')
          $option.val(option['PRES_NAME'])
          $option.text(option['PRES_NAME'])
          $option.attr('rowkey', option['rowkey'])
          $(select).append($option)
        })
        //设置默认选中
        $(select).val(role)
        $(select).attr('rowkey', rowKey)
      },
      error: function () {
        var $div = $('<div></div>')
        $div.PreWebSuccessModel({ data: '请求失败，请联服务器管理员！' })
      },
    })
  }

  /*创建节点的方法*/
  function CrateStep(StepId) {
    $('#' + divID).mousemove(function (e) {
      var yy = e.clientY - $(this).offset().top
      var xx = e.clientX - $(this).offset().left
      var uuid = PresoftUUID(32, 0)
      if (StepId == 'start') {
        shapes[i] = r
          .image('images/start48.png', xx, yy, 40, 40)
          .attr({ cursor: 'move' })
        shapes[i].name = '开始'
        shapes[i].text = r
          .text(xx + 50, yy + 25, '')
          .attr({ font: '14px "Arial"', 'fill-opacity': 1, cursor: 'move' })
      } else if (StepId == 'link') {
        shapes[i] = r.rect(xx, yy, 100, 50, 4).attr({
          fill: '#f6f7ff',
          stroke: '#808080',
          'stroke-width': '2px',
          'fill-opacity': 1,
          cursor: 'move',
          opacity: '.4',
        })
        shapes[i].name = '环节'
        shapes[i].text = r.text(xx + 50, yy + 25, '环节').attr({
          font: '14px "Arial"',
          'fill-opacity': 1,
          cursor: 'move',
        })
        shapes[i].toFront()
      } else if (StepId == 'countersign') {
        shapes[i] = r.rect(xx, yy, 100, 50, 4).attr({
          fill: '#f6f7ff',
          stroke: '#187142',
          'stroke-width': '3px',
          'fill-opacity': 1,
          cursor: 'move',
          opacity: '.4',
        })
        shapes[i].name = '会签'
        shapes[i].text = r.text(xx + 50, yy + 25, '会签').attr({
          font: '14px "Arial"',
          'fill-opacity': 1,
          cursor: 'move',
        })
        shapes[i].toFront()
      } else if (StepId == 'end') {
        shapes[i] = r
          .image('images/stop48.png', xx, yy, 40, 40)
          .attr({ cursor: 'move' })
        shapes[i].name = '结束'
        shapes[i].text = r
          .text(xx + 50, yy + 25, '')
          .attr({ font: '14px "Arial"', 'fill-opacity': 1, cursor: 'move' })
      }
      shapes[i].stepType = StepId
      shapes[i].id = uuid
      shapes[i].rowkey = str + 'wfstepobj/' + uuid
      shapes[i].desc = ''
      shapes[i].index = i
      shapes[i].dealRole = []
      shapes[i].dealRoleRowKey = []

      shapes[i].PRES_CATEGORY = 'wfstepobj'

      shapes[i].text.id = 'text' + uuid
      texts.push(shapes[i].text)
      AllStepAndPath.push(shapes[i])

      assist = AllStepAndPath
      $('#' + divID).unbind('mousemove')

      shapes[i].drag(move, dragger, up)
      $('#' + divID).unbind('mousemove')
      //单击事件
      shapes[i].click(function () {
        var sh = this
        $.each(shapes, function (idx, oneshape) {
          if (!oneshape) {
          } else {
            if (sh == oneshape) {
              oneshape.attr('stroke', 'red')
            } else {
              if (oneshape.stepType == 'countersign') {
                oneshape.attr('stroke', '#187142')
              } else {
                oneshape.attr('stroke', '#808080')
              }
            }
          }
        })
        var arrto = setobj(s, this, obj1, obj2, connections, r, n, str)
        if (arrto.length == 2) {
          s = arrto[0]
          obj1 = arrto[1]
        } else {
          s = arrto[0]
        }
      })
      //定义双击弹框事件
      shapes[i].dblclick(function () {
        var sh = this
        if ($('#props').length > 0) {
          $('#props').remove()
        }
        var $props = $('<div id="props" class="workflow_props"></div>')
        var $form = $('<div class="form"></div>')
        var $xianshi = $('<div style="margin-top: 5px"></div>')
        var $lable1 = $('<label class="raphael_lable ver_align">名称</label>')
        var $input = $(
          '<input type="text" style="width: 150px" class="raphael_input ver_align form-control_wf">'
        )
        var $desc = $('<div style="margin-top: 5px"></div>')
        var $lable2 = $(
          '<label style="padding-bottom: 15px;" class="raphael_lable ver_align">描述</label>'
        )
        var $texta = $(
          '<textarea class="raphael_texta ver_align form-control_wf" style="width:150px' +
            '" cols="20" rows="2"></textarea>'
        )
        var $sqjsDiv = $('<div style="margin-top: 5px"></div>')
        var $label3 = $('<label for="name">审签角色</label>')
        var $checkDiv = $('<div></div>')
        var $select = $('<select multiple class="form-control"></select>')
        var $enter_cancle = $('<div class="raphael_btn"></div>')
        var $enterbut = $(
          '<input type="button" class="btn btn-success" style="margin-left: 27px;" ' +
            'id="confirm" value="确定">'
        )
        var $canclebut = $(
          '<input type="button" class="btn" id="cancle" style="margin-left: 27px"' +
            ' value="取消">'
        )
        $xianshi.append($lable1)
        $xianshi.append($input)
        $desc.append($lable2)
        $desc.append($texta)
        $sqjsDiv.append($label3).append($checkDiv)
        $checkDiv.append($select)
        $enter_cancle.append($enterbut)
        $enter_cancle.append($canclebut)
        $form
          .append($xianshi)
          .append($desc)
          .append($sqjsDiv)
          .append($enter_cancle)
        $props.append($form)
        $(main).append($props)

        setOption($select, this.dealRole, this.dealRoleRowKey)

        $props.css('display', 'block')
        $input.val(this.name)
        $texta.val(this.desc)

        console.log(this.text)
        var x = this.text.attrs.x
        var y = this.text.attrs.y
        //点击确定以后
        $enterbut.click(function () {
          sh.name = $input.val()
          sh.desc = $texta.val()
          if ($select.val == null) {
            sh.dealRole = []
            sh.dealRoleRowKey = []
          } else {
            sh.dealRole = $select.val()
            var arr = []
            $.each($select.find('option:selected'), function (i, op) {
              arr.push($(op).attr('rowkey'))
            })
            sh.dealRoleRowKey = arr
          }
          console.log(sh.dealRole)
          console.log(sh.dealRoleRowKey)
          if (sh.name != '开始' && sh.name != '结束') {
            if ('text' + sh.id == sh.text.id) {
              sh.text.remove()
            }
            shapes[sh.index].text = r.text(x, y, $input.val()).attr({
              font: '14px "Arial"',
              'fill-opacity': 1,
            })
            shapes[sh.index].text.id = 'text' + sh.id
            shapes[sh.index] = sh
            texts.push(shapes[sh.index].text)
            shapes[sh.index].toFront()
          } else {
            shapes[sh.index] = sh
          }
          console.log(shapes[sh.index])
          $props.remove()
        })
        //取消属性框
        $canclebut.click(function () {
          $props.remove()
        })
      })
      i = i + 1
      console.log(i)
    })
  }

  // 撤回按钮，定时刷新AllStepAndPath，assist
  $('#recall').click(function () {
    recall()
    var txt = window.setInterval(function () {
      if (AllStepAndPath.length != assist.length) {
        assist = AllStepAndPath
      }
    }, 500)
  })

  // 撤回方法，删除数组中的最后一个对象
  function recall() {
    var length = assist.length
    var ro = AllStepAndPath[length - 1].rowkey
    for (var j = 0; j < texts.length; j++) {
      if ('text' + AllStepAndPath[length - 1].id == texts[j].id) {
        texts[j].remove()
        console.log('text.remove正常-----------------------')
      }
    }
    var sp = AllStepAndPath[length - 1]
    if (sp.PRES_CATEGORY == 'wfstepobj') {
      shapes.length = shapes.length - 1
      AllStepAndPath[length - 1].remove()
    } else {
      savePath.length = savePath.length - 1
      AllStepAndPath[length - 1].remove()
    }
    if (length > 0) {
      AllStepAndPath.length = length - 1
    }
  }

  // 转换按钮，状态转换，处于连线中的状态
  $('#path').click(function () {
    s = 0
    obj1.length = 0
    obj2.length = 0
    n = 1
    $stateSpan.css('color', '#5FB878')
    $stateSpan.text('状态:连线中')
    console.log(obj1.length + '------------')
  })
  // 选择按钮，点击后状态切换到选择元素
  $('#pointer').click(function () {
    n = 0
    $stateSpan.css('color', '#191940')
    $stateSpan.text('状态:选择元素')
  })
  // 重绘，点击后清空流程图
  $('#myflow_reset').click(function () {
    saveStep = []
    savePath = []
    if (AllStepAndPath.length > 0) {
      $.each(AllStepAndPath, function (idx, itemData) {
        itemData.remove()
      })
      $.each(shapes, function (idx, itemData) {
        shapes.length--
      })
    }
    if (texts.length > 0) {
      $.each(texts, function (idx, itemData) {
        itemData.remove()
      })
    }
  })
  // 保存
  $('#myflow_save').click(function () {
    //首先清空saveStep
    saveStep = []
    var json = JSON.stringify(getFormResult($('#flow_form_save')))
    var obj = JSON.parse(json)
    if (
      obj.PRES_ID != '' &&
      obj.PRES_NAME != '' &&
      obj.PRES_DESC != '' &&
      shapes.length > 0 &&
      savePath.length > 0
    ) {
      //uuid0是点击保存时生成该条模板的rowkey的uuid
      var uuid0 = PresoftUUID(32, 0)
      console.log(uuid0)
      for (var i = 0; i < shapes.length; i++) {
        if (!shapes[i]) {
        } else {
          var saveSon = {}
          saveSon.rowkey = shapes[i].rowkey
          saveSon.PRES_ID = shapes[i].id
          saveSon.PRES_NAME = shapes[i].name
          saveSon.PRES_DESC = shapes[i].desc
          saveSon.PRES_DEAL_ROLE = shapes[i].dealRole
          saveSon.PRES_DEAL_ROLEROWKEY = shapes[i].dealRoleRowKey
          saveSon.PRES_CATEGORY = 'wfstepobj'
          saveSon.PRES_STEPTYPE = shapes[i].stepType
          saveSon.PRES_X = shapes[i].attrs.x
          saveSon.PRES_Y = shapes[i].attrs.y
          saveSon.PRES_WIDTH = shapes[i].attrs.width
          saveSon.PRES_HEIGHT = shapes[i].attrs.height
          saveSon.PRES_PARENT = url + '/' + uuid0
          saveSon.PRES_MARK = PresoftUUID(32, 0)
          saveSon.PRES_SORT = i
          saveSon.PRES_STATUS = 'INWORK'
          saveStep.push(saveSon)
        }
      }
      $.each(savePath, function (idx, onepath) {
        onepath.PRES_PARENT = url + '/' + uuid0
      })
      obj.Step = saveStep
      obj.Path = savePath

      var str = rowkey
      // 截取字符串中最后一个"/"后的内容, str
      var index = str.lastIndexOf('/')
      str = str.substring(index + 1, str.length)
      obj.PRES_CATEGORY = str
      obj.rowkey = url + '/' + uuid0
      console.log(obj)
      var data = JSON.stringify(obj)
      $.ajax({
        url: obj.rowkey,
        type: 'post',
        data: data,
        dataType: 'json',
        success: function (responseData) {
          var message = responseData.response.message
          toastr.success(message)
          refreshObjectPage('/preplatform/prewf/wftpcom/wftp/allwftemplate')
        },
        error: function () {
          toastr.error('请求失败，请联系管理员！')
        },
      })
    } else {
      toastr.warning('请完善数据！')
    }
  })
}

/*绘制path的方法*/
function setobj(s, shape, obj1, obj2, connections, r, n, str) {
  if (s == 0) {
    var arr = []
    obj1.length = 0
    obj1[0] = shape
    s = 1
    arr[0] = s
    arr[1] = obj1
    return arr
  }
  if (s == 1) {
    var arr = []
    obj2.length = 0
    obj2[0] = shape
    s = 0
    if (n == 1) {
      console.log(n)
      var saveps = {}
      var uuid = PresoftUUID(32, 0)
      saveps.PRES_CATEGORY = 'wfpathobj'
      saveps.rowkey = str + 'wfpathobj/' + uuid
      saveps.fromstep = obj1[0].rowkey
      saveps.tostep = obj2[0].rowkey
      savePath.push(saveps)
      var path = r.drawArr({ obj1: obj1[0], obj2: obj2[0] })
      connections.push(path)
    }
    arr[0] = s
    return arr
  }
}
